import pyaudio
import numpy as np
import time

def count_hits(audio_data, threshold):
    # 计算绝对值大于阈值的样本点个数
    hits = np.sum(np.abs(audio_data) > threshold)
    return hits

def record_audio(fs, duration):
    audio = pyaudio.PyAudio()

    # 打开音频输入流
    stream = audio.open(format=pyaudio.paInt16,
                        channels=1,
                        rate=fs,
                        input=True,
                        frames_per_buffer=1024)

    frames = []
    for i in range(int(fs / 1024 * duration)):
        # 读取音频数据
        data = stream.read(1024)
        frames.append(data)

    # 关闭流和音频
    stream.stop_stream()
    stream.close()
    audio.terminate()

    # 将帧数据合并为一个连续的数组
    audio_data = np.frombuffer(b"".join(frames), dtype=np.int16)
    return audio_data

fs = 44100  # 采样率
duration = 1  # 录制时长（秒）
threshold = 1000  # 阈值

# 录制音频数据
audio_data = record_audio(fs, duration)

# 计算击键次数
hits = count_hits(audio_data, threshold)

print(f"敲击次数: {hits}")
